package com.sanq.product.books.interceptors;

import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.utils.WebUtil;
import com.sanq.product.config.utils.date.LocalDateUtils;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.config.utils.web.LogUtil;
import com.sanq.product.redis.service.JedisPoolService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * com.sanq.product.books.interceptors.SecurityInterceptor
 *
 * @author sanq.Yan
 * @date 2019/7/9
 */
public class SecurityInterceptor extends com.sanq.product.security.interceptors.SecurityInterceptor {

    @Resource
    private JedisPoolService jedisPoolService;
    private static final int MAX = 60;  //最大限制  1分钟访问60次

    @Override
    public boolean checkToken(HttpServletRequest request, String token) {
        boolean exists = jedisPoolService.exists(Redis.ReplaceKey.getTokenUser(token));
        if (exists) {
            //记录活跃用户
            String activeUsersKey = Redis.ReplaceKey.getActiveUsers(LocalDateUtils.nowTime());
            UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(Redis.ReplaceKey.getTokenUser(token)), UsersVo.class);
            jedisPoolService.setBit(activeUsersKey, usersVo.getId(), true);
        }
        return exists;
    }

    @Override
    public boolean checkIp(HttpServletRequest request, String ip) {
        String ipKey = Redis.ReplaceKey.getCheckIpKey(ip, request.getRequestURI());

        if (jedisPoolService.zrank(Redis.RedisKey.BLOCK_IP_SET, ip)) {
            LogUtil.getInstance(SecurityInterceptor.class).i("ip进入了黑名单");
            return true;
        }


        String ipCountTmp = jedisPoolService.get(ipKey);
        int ipCount = StringUtil.toInteger(ipCountTmp != null ? ipCountTmp : 0);

        if (ipCount > MAX) {
            jedisPoolService.putSet(Redis.RedisKey.BLOCK_IP_SET, 1, ip);
            jedisPoolService.delete(ipKey);
            return true;
        }

        jedisPoolService.incrAtTime(ipKey, MAX);

        return false;
    }
}
